<template>
  <Header
      :style="{
            position: 'fixed',
            width: '100%',
            height: '48px',
            backgroundColor: 'rgba(33,33,33,.8)',
            lineHeight: '48px',
            padding: '0 20px 0px 0px',
            zIndex: 66
          }" @click.stop.native="headerClickHandle">

    <PreviewFrame :show="previewFrameVisible" :src="previewFrameSrc" @cancel="previewFrameVisible = false"></PreviewFrame>

    <Tooltip class="header-title" :content="'最后更新日期：'+pageMetadata.create_date" placement="bottom">
      <h2 v-if="pageMetadata.id"><Icon type="md-browsers" style="display: inline-block; margin-top: -3px;"/> - {{pageMetadata.name}} </h2>
    </Tooltip>

    <div class="back-home-btn" @click="$router.push('/')">
      <Icon type="ios-arrow-back" />
    </div>

    <div class="project-info-btn">
      <span>工程信息</span>
      <div class="project-tree-wrap">
        <Button size="small" type="primary" style="margin: 0px 5px 0px 5px;"
                @click="openAndCloseCreatePageDrawer(true)" icon="md-add">新建页面</Button>
        <p v-if="pageTreeData.length == 0" style="text-align: center">此工程下无相关页面</p>
        <div class="page-tree-card-wrapper">
          <div class="page-tree-card" v-for="(page, index) in pageTreeData" :key="index">
            <div :class="{'page-icon': true, 'active': pageMetadata.id == page.id}">
              <Icon :custom="developCanvasIcon(page.develop_canvas)"/>
            </div>
            <div class="page-toolbar">
              <div title="复制链接" class="toolbar-btn" @click="copyPageLink(page.path)"><Icon custom="iconfont icon-copy-link" size="13"/></div>
              <div title="拷贝页面" class="toolbar-btn" @click="copyPage(page.id)"><Icon type="md-copy" size="14"/></div>
              <div title="删除" class="toolbar-btn" @click="deletePage(page.id)"><Icon type="md-trash" size="14"/></div>
            </div>
            <div class="page-info" @click="openPageToDesigner(page.id)">
              {{$PnUtil.cutString(page.name, 18)}}
            </div>
          </div>
        </div>
      </div>
    </div>

    <Tooltip transfer :content="'结构树'" placement="bottom">
      <Button class="m-r-5px" size="small"
              :type="structureTreeSidebarCollapsed ? 'default':'primary'"
              @click="toggleStructureTreeSidebarCollapsed">
        <Icon custom="iconfont icon-coverage"/>
      </Button>
    </Tooltip>

    <Tooltip transfer :content="'组件库'" placement="bottom">
      <Button size="small"
              :type="componentLibrarySidebarCollapsed ? 'default':'primary'"
              @click="toggleComponentLibrarySidebarCollapsed">
        <Icon custom="iconfont icon-component" size="15"/>
      </Button>
    </Tooltip>

    <Divider type="vertical"></Divider>

    <Tooltip transfer :content="'保存'" placement="bottom">
      <Button class="" size="small" type="success"
            :disabled="!pageMetadata.id"
            @click="saveCurrentEditPage"><Icon custom="iconfont iconsave-fill"/></Button>
    </Tooltip>

    <Divider type="vertical"></Divider>

    <Tooltip transfer :content="'撤销、单步恢复'" placement="bottom">
      <ButtonGroup size="small" class="m-r-5px">
        <Button size="small" type="primary"
                :disabled="!pageMetadata.id"
                @click="stepBackward"><Icon type="md-undo" size="14"/></Button>
        <Button size="small" type="primary"
                :disabled="!pageMetadata.id"
                @click="stepRecover"><Icon type="md-redo" size="14"/></Button>
      </ButtonGroup>
    </Tooltip>

    <Dropdown :transfer="false" placement="bottom-start" trigger="hover" transfer-class-name="dropdown-menu-no-overflow"
              @on-click="otherDropdownClickHandler">
      <Button type="primary" size="small">
        <Icon type="ios-more" size="14"/>
        <!--<Icon type="ios-arrow-down"></Icon>-->
      </Button>
      <DropdownMenu slot="list">
        <DropdownItem :disabled="!pageMetadata.id" name="saveDraft"><Icon custom="iconfont icondraft"/> 存为草稿</DropdownItem>
        <DropdownItem :disabled="!pageMetadata.id" name="loadDraft"><Icon custom="iconfont iconread"/> 加载草稿</DropdownItem>
        <DropdownItem :disabled="!pageMetadata.id" name="clearCanvas" divided><Icon custom="iconfont iconqingkong"/> 清空画布</DropdownItem>
        <DropdownItem :disabled="!pageMetadata.id" name="clearLocalStorage"><Icon custom="iconfont iconqingkonghuancun"/> 清空本地存储</DropdownItem>
        <DropdownItem :disabled="!pageMetadata.id" name="showSourceDataDrawerVisible"><Icon custom="iconfont iconjson"/> 页面源数据</DropdownItem>
      </DropdownMenu>
    </Dropdown>

    <Divider type="vertical"></Divider>

    <Tooltip v-if="pageMetadata.develop_canvas != 'FormLayoutCanvas'" transfer :content="'预设结果集过滤器管理'" placement="bottom">
      <Button class="m-r-5px" size="small" type="primary"
            @click="filterManageDrawerVisible = !filterManageDrawerVisible"><Icon type="ios-funnel" style="margin-top: 4px;"/></Button>
    </Tooltip>

    <Tooltip v-if="pageMetadata.develop_canvas != 'FormLayoutCanvas'" transfer :content="'当前编辑页面动态数据源配置管理'" placement="bottom">
      <Button class="m-r-5px" size="small" type="primary"
              :disabled="!pageMetadata.id"
              @click="dataSourceGlobalSettingVisible = !dataSourceGlobalSettingVisible"><Icon custom="iconfont icon-datasource-setting"/></Button>
    </Tooltip>

    <Poptip v-if="pageMetadata.develop_canvas != 'FormLayoutCanvas'" transfer placement="bottom"
            @on-popper-show="updateCompModalVisible = true"
            @on-popper-hide="updateCompModalVisible = false">
      <Tooltip transfer :content="'升级组件'" placement="bottom">
        <Button size="small" class="" type="primary"
              :disabled="!pageMetadata.id" >
          <Badge :count="renewableCompsNum" :offset="[-5,-5]">
            <Icon type="md-refresh" size="15"/>
          </Badge>
        </Button>
      </Tooltip>
      <div slot="content">
        <UpdateCompModal :show="updateCompModalVisible"
                         :layout-items="pageMetadata.layout.layoutItems"></UpdateCompModal>
      </div>
    </Poptip>

    <Divider v-if="pageMetadata.develop_canvas != 'FormLayoutCanvas'" type="vertical"></Divider>

    <Tooltip v-if="pageMetadata.develop_canvas != 'FormLayoutCanvas'" transfer :content="'主题美化'" placement="bottom">
      <Button size="small" class="m-r-5px" type="primary"
              :disabled="!pageMetadata.id"
              @click="openChangeThemeDrawer"><Icon custom="iconfont icon-theme-beautify"/></Button>
    </Tooltip>

    <Tooltip transfer :content="'页面全局样式'" placement="bottom">
      <Button size="small" class="m-r-5px" type="primary"
              :disabled="!pageMetadata.id"
              @click="pageGlobalStyleDrawerVisible = !pageGlobalStyleDrawerVisible"><Icon custom="iconfont icon-css"/></Button>
    </Tooltip>

    <Tooltip v-if="pageMetadata.develop_canvas != 'FormLayoutCanvas'" transfer :content="'页面全局JS脚本'" placement="bottom">
      <Button size="small" class="m-r-5px" type="primary"
              :disabled="!pageMetadata.id"
              @click="pageGlobalJsDrawerVisible = !pageGlobalJsDrawerVisible"><Icon type="logo-javascript" size="14"/></Button>
    </Tooltip>

    <Tooltip transfer :content="'收藏为模板'" placement="bottom">
      <Button size="small" class="" type="primary"
              :disabled="!pageMetadata.id"
              @click="openPageTemplateForm"><Icon type="md-heart" size="14"/></Button>
    </Tooltip>

    <!--<Divider type="vertical"></Divider>

    <Button title="存为模板" class="m-r-5px" size="small" type="primary"
            :disabled="!$store.state.designer.pageMetadata.id"
            @click=""><Icon custom="iconfont icon-save-page-template"/></Button>-->

    <div :style="{float: 'right'}">

      <Tooltip transfer :content="'当前窗口预览、新窗口预览'" placement="bottom">
        <ButtonGroup class="m-r-5px" size="small">
          <Button size="small" type="primary"
                  :disabled="!pageMetadata.id"
                  @click="previewPage('self')"><Icon custom="iconfont icondesktop"/></Button>
          <Button size="small" type="primary"
                  :disabled="!pageMetadata.id"
                  @click="previewPage('blank')"><Icon custom="iconfont icon-open-to-new-window"/></Button>
        </ButtonGroup>
      </Tooltip>

      <Tooltip transfer content="快照管理" placement="bottom">
        <Button size="small" type="primary" class="m-r-5px"
                :disabled="!pageMetadata.id"
                @click="pageSnapshootManageDrawerVisible = !pageSnapshootManageDrawerVisible"><Icon type="logo-instagram" size="15" style="margin-top: 3px;"/></Button>
      </Tooltip>

      <Tooltip transfer :content="'发布'" placement="bottom">
        <Button size="small" type="primary"
                :disabled="!pageMetadata.id"
                @click="openReleasePageFormModal"><Icon custom="iconfont icon-send"/></Button>
      </Tooltip>

      <Divider type="vertical"></Divider>

      <Tooltip transfer :content="'页面导出、导入'" placement="bottom">
        <ButtonGroup size="small">
          <Button size="small" type="primary"
                  :disabled="!pageMetadata.id"
                  @click="exportPage">
            <Icon custom="iconfont icon-download"/>
          </Button>
          <Button size="small" type="primary" @click="openImportPageModal">
            <Icon custom="iconfont icon-import-page"/>
          </Button>
        </ButtonGroup>
      </Tooltip>

      <Divider type="vertical"></Divider>

      <Tooltip transfer :content="'页面更新操作日志'" placement="bottom-end">
        <Button :disabled="!pageMetadata.id" class="m-r-5px" size="small" type="primary" @click="openPageLogOperateDrawer()">
          <Icon type="md-paper" size="14"/>
        </Button>
      </Tooltip>

      <Tooltip transfer :content="'全局设置'" placement="bottom-end">
        <Button class="m-r-5px" size="small" type="primary"
                @click="globalConfigDataDrawerVisible = !globalConfigDataDrawerVisible">
          <Icon type="md-settings" size="14"/>
        </Button>
      </Tooltip>

      <Tooltip transfer :content="'右侧边栏'" placement="bottom-end">
        <Button class="m-r-5px" size="small"
                :type="rightSidebarCollapsed ? 'default':'primary'"
                @click="toggleRightSidebarCollapsed">
          <Icon custom="iconfont icon-right-sidebar"/>
        </Button>
      </Tooltip>

    </div>

    <Drawer
        title="新建页面"
        v-model="createPageDrawerVisible"
        width="70%"
        :mask-closable="false"
        :styles="$PnUtil.buildDrawerStyleByHasFooter()">
      <PageForm ref="pageForm"></PageForm>
      <DrawerFooter>
        <Button style="margin-right: 8px" @click="openAndCloseCreatePageDrawer(false)">关闭</Button>
        <Button type="primary" @click="submitPageForm">保存</Button>
      </DrawerFooter>
    </Drawer>

    <Drawer title="预设结果集过滤器管理"
            width="450"
            placement="left"
            :closable="false"
            :z-index="888"
            v-model="filterManageDrawerVisible">
    <FilterManage></FilterManage>
    </Drawer>

    <DataSourceGlobalSetting ref="dataSourceGlobalSetting"
                             :show="dataSourceGlobalSettingVisible"
                             @cancel="dataSourceGlobalSettingVisible = false"></DataSourceGlobalSetting>

    <Drawer
        title="全局配置"
        v-model="globalConfigDataDrawerVisible"
        width="330"
        :mask-closable="true">
      <GlobalConfigDataForm></GlobalConfigDataForm>
    </Drawer>

    <Drawer title="源数据"
            placement="left"
            v-model="sourceDataDrawerVisible"
            :draggable="true"
            :closable="false"
            :mask-closable="true"
            width="450">
      <Alert type="error">非特殊情况不要在此直接编辑源数据！</Alert>
      <div style="background-color: #fff;">
        <PnJsonEditor v-model="pageMetadata"></PnJsonEditor>
      </div>
    </Drawer>

    <ChangeThemeDrawer ref="changeThemeDrawer"
                       :show="changeThemeDrawerVisible"
                       @cancel="changeThemeDrawerVisible = false"></ChangeThemeDrawer>

    <PageTemplateForm ref="pageTemplateForm"></PageTemplateForm>

    <PageSnapshootManageDrawer :show="pageSnapshootManageDrawerVisible"
                               @cancel="pageSnapshootManageDrawerVisible = false"></PageSnapshootManageDrawer>

    <ReleasePageFormModal ref="releasePageFormModal"
                          :show="releasePageFormModalVisible"
                          @cancel="releasePageFormModalVisible = false"></ReleasePageFormModal>

    <Modal
        v-model="importPageModalVisible"
        title="导入页面"
        :footer-hide="true">
      <ImportPage ref="importPageModal" @upload-success="importPageSuccessHandle"></ImportPage>
    </Modal>

    <PageGlobalStyleDrawer :show="pageGlobalStyleDrawerVisible" @cancel="pageGlobalStyleDrawerVisible = false"></PageGlobalStyleDrawer>
    <PageGlobalJsDrawer :show="pageGlobalJsDrawerVisible" @cancel="pageGlobalJsDrawerVisible = false"></PageGlobalJsDrawer>

    <PageLogOperateDrawer ref="PageLogOperateDrawer"></PageLogOperateDrawer>

    <div class="along-comp-edit-model-mask-layer" v-if="isAlongCompEditModel">
      <Button type="success" size="small" @click="quitAlongCompEditModel">应用独立组件编辑模式下的编辑状态</Button>
    </div>

  </Header>
</template>

<script>
  import PnJsonEditor from '../../../components/common/PnJsonEditor'

  import FilterManage from '../admin/filter/FilterManage'
  import GlobalConfigDataForm from './common/GlobalConfigDataForm'
  import ReleasePageFormModal from './common/ReleasePageFormModal'
  import ChangeThemeDrawer from "./common/ChangeThemeDrawer"
  import PageTemplateForm from "../admin/pageTemplate/PageTemplateForm"
  import PageForm from '../admin/page/PageForm'
  import PreviewFrame from "./common/PreviewFrame";
  import UpdateCompModal from "./common/UpdateCompModal"
  import ImportPage from "../admin/page/ImportPage";
  import DataSourceGlobalSetting from './common/DataSourceGlobalSetting'
  import PageSnapshootManageDrawer from './common/PageSnapshootManageDrawer'
  import PageGlobalStyleDrawer from "@/views/components/designer/common/PageGlobalStyleDrawer"
  import PageGlobalJsDrawer from "@/views/components/designer/common/PageGlobalJsDrawer"
  import PageLogOperateDrawer from "@/views/components/designer/common/PageLogOperateDrawer"

  import { createHelpers } from 'vuex-map-fields';


  const { mapFields } = createHelpers({
    getterType: 'designer/getField',
    mutationType: 'designer/updateField',
  });

  export default {
    name: 'DesignerHeader',
    components: {
      PnJsonEditor,
      FilterManage,
      GlobalConfigDataForm,
      ReleasePageFormModal,
      ChangeThemeDrawer,
      PageTemplateForm,
      PageForm,
      PreviewFrame,
      UpdateCompModal,
      ImportPage,
      DataSourceGlobalSetting,
      PageSnapshootManageDrawer,
      PageGlobalStyleDrawer,
      PageGlobalJsDrawer,
      PageLogOperateDrawer
    },
    data() {
      return {
        previewFrameVisible: false,
        previewFrameSrc: '',

        createPageDrawerVisible: false,
        globalConfigDataDrawerVisible: false,
        sourceDataDrawerVisible: false,
        filterManageDrawerVisible: false,
        dataSourceGlobalSettingVisible: false,
        releasePageFormModalVisible: false,
        changeThemeDrawerVisible: false,
        updateCompModalVisible: false,
        importPageModalVisible: false,
        pageSnapshootManageDrawerVisible: false,
        pageGlobalStyleDrawerVisible: false,
        pageGlobalJsDrawerVisible: false,

        pageTreeData: [], // 页面信息树
        currentSelectPageId: '', // 当前选中页面的ID

        renewableCompsNum: 0, // 可更新组件数量

        autoSavePageTimer: null,  // 页面自动保存定时器
      }
    },
    mounted() {

      this.loadProjectInfo().then(()=>{
        this.initPageTreeData();
      });

      this.initAllCompinfoToStorage();

      if (this.$route.query['page_id']) {
        this.openPageToDesigner(this.$route.query['page_id']);
      }

      this.$EventBus.$on('pn_save_current_page', () => {
        this.saveCurrentEditPage()
      });

    },
    destroyed() {
      clearInterval(this.autoSavePageTimer)
    },
    methods: {

      developCanvasIcon(develop_canvas) {
        switch (develop_canvas) {
          case 'AbsoluteLayoutCanvas':
            return 'iconfont icon-absolute-layout'
          case 'ReactiveLayoutCanvas':
            return 'iconfont icon-reactive-layout'
          case 'FormLayoutCanvas':
            return 'iconfont icon-form-layout'
        }
        return ''
      },

      headerClickHandle () {
        this.$EventBus.$emit('pn_headerClick')
      },

      toggleStructureTreeSidebarCollapsed () {
        this.$store.commit('designer/toggleStructureTreeSidebarCollapsed')
      },

      toggleComponentLibrarySidebarCollapsed () {
        this.$store.commit('designer/toggleComponentLibrarySidebarCollapsed')
      },

      toggleRightSidebarCollapsed () {
        this.$store.commit('designer/toggleRightSidebarCollapsed');
      },

      /**
       * 加载工程信息并存入vuex
       */
      async loadProjectInfo () {
        return await this.$PnApi.ProjectApi.getProjectById(this.$route.query.project_id).then(result=>{
          this.$store.commit('designer/setProjectInfo', result.data.payload);
        })
      },

      /**
       * 初始化加载所有组件的缩略图信息保存至本地存储，目的是为了在设计器结构树中，获取对应组件的缩略图
       */
      initAllCompinfoToStorage () {
        this.$PnApi.CompinfoApi.getAllCompinfo().then(result => {
          let obj = {};
          result.data.payload.forEach(item => {
            obj[item.name] = {
              alias_name: item.alias_name,
              thumbnail_uri: item.thumbnail_uri
            }
          });
          localStorage.setItem('allCompinfoObj', JSON.stringify(obj))
        })
      },

      /**
       * 初始化页面信息树数据
       */
      initPageTreeData () {
        this.$PnApi.PageApi.getPagesByProjectId(this.projectInfo.id).then(result => {
          this.pageTreeData = result.data.payload;
        })
      },

      openAndCloseCreatePageDrawer (open) {
        if (open) {
          this.createPageDrawerVisible = !this.createPageDrawerVisible;
          this.$refs.pageForm.loadPageTemplates()
        }else {
          this.$refs.pageForm.clearPageForm();
          this.createPageDrawerVisible = false;
        }
      },

      submitPageForm () {
        this.$refs.pageForm.$refs.form.validate((valid) => {
          if (valid) {
            let pageFormData = this.$refs.pageForm.formData;
            pageFormData.path = '/' + this.$PnUtil.getTimestamp();
            pageFormData.component = pageFormData.develop_canvas.replace('Canvas', '');
            // pageFormData.develop_canvas = 'AbsoluteLayoutCanvas';
            pageFormData.project_id = this.$route.query.project_id; // 赋值工程ID

            if (!pageFormData.layout) {
              if (pageFormData.develop_canvas == 'AbsoluteLayoutCanvas') {
                let layout = {
                  id: this.$PnUtil.uuid(),
                  layoutConfigData: {},
                  layoutGroup: [],
                  layoutItems: []
                };
                layout.layoutConfigData = this.$DesignerCommonUtil.buildAbsoluteLayoutConfigData();
                pageFormData.layout = JSON.stringify(layout);
              }else if (pageFormData.develop_canvas == 'ReactiveLayoutCanvas') {
                let layout = {
                  id: this.$PnUtil.uuid(),
                  layoutConfigData: {},
                  layoutItems: []
                };
                layout.layoutConfigData = this.$ReactiveDesignerCommonUtil.buildReactiveLayoutConfigData();
                pageFormData.layout = JSON.stringify(layout);
              }else if (pageFormData.develop_canvas == 'FormLayoutCanvas') {
                let layout = {
                  id: this.$PnUtil.uuid(),
                  layoutConfigData: {},
                  layoutItems: []
                }
                layout.layoutConfigData = this.$FormDesignerCommonUtil.buildFormLayoutConfigData();
                pageFormData.layout = JSON.stringify(layout);
              }
            }

            this.$PnApi.PageApi.savePage(pageFormData, this.$refs.pageForm.currentSelectedTemplateId).then((result)=>{
              if(result.data.success) {
                this.$Message.success(result.data.message);
                this.$refs.pageForm.clearPageForm();
                this.createPageDrawerVisible = false;
                this.initPageTreeData();
                this.openPageToDesigner(result.data.payload)
              }else {
                this.$Message.error(result.data.message)
              }
            });
          }
        });
      },

      pageTreeSelectChangeHandle (selectPages) {
        if(selectPages.length > 0) {
          this.currentSelectPageId = selectPages[0].key
        }else {
          this.currentSelectPageId = ''
        }
      },

      /**
       * 打开页面并编辑，在这里将会初始化vuex中的pageMetadata数据
       */
      openPageToDesigner (pageId) {
        let handler = (pageId) => {
          sessionStorage.removeItem('redrawChartRunning');

          this.$store.commit('designer/setRightSidebarPageConfigFormName', 'PageFormForDesigner');
          this.$store.commit('designer/resetDesigner');
          this.$store.dispatch('designer/loadPage', pageId).then(() => {
            // 如果不是表单布局设计器，则执行下面的逻辑加载当前页面中可升级的组件数量
            if (this.pageMetadata.develop_canvas != 'FormLayoutCanvas') {
              let loadRenewableCompsNum = () => {
                this.renewableCompsNum = this.$DesignerCommonUtil.loadRenewableComps(this.pageMetadata.layout.layoutItems).length
              };
              loadRenewableCompsNum();
              this.$EventBus.$on('pn_update_comps_success', () => {
                loadRenewableCompsNum()
              })
            }
          });

          this.currentSelectPageId = pageId;

          // 将页面ID添加至URL参数中
          this.$PnUtil.addUrlParams('page_id', pageId);
        };
        if (this.pageMetadata.id) {
          this.$Modal.confirm({
            title: '提醒',
            content: '切换页面系统不会自动保存您所做的改动，请确认是否已保存。',
            onOk: () => {
              handler(pageId)
            }
          });
        }else {
          handler(pageId)
        }
      },

      copyPageLink (path) {
        let cont = window.location.protocol + '//' + window.location.host + window.g.PROJECT_ROOT_NAME + path;
        this.$PnUtil.copyToClipboard(cont);
        this.$Message.success('页面链接（'+cont+'）复制成功')
      },

      copyPage (pageId) {
        this.$Modal.confirm({
          title: '确认',
          content: '确定拷贝此页面至当前工程下吗？',
          onOk: () => {
            this.$PnApi.PageApi.copyPage(this.projectInfo.id, pageId).then(result => {
              if (result.data.success) {
                this.$Message.success(result.data.message);
                this.initPageTreeData();
              }else {
                this.$Message.error(result.data.message)
              }
            })
          }
        });
      },

      deletePage(pageId) {
        this.$Modal.confirm({
          title: '提醒',
          content: '确认删除此页面吗？',
          onOk: () => {
            this.$PnApi.PageApi.deletePage(pageId).then(result=>{
              if(result.data.success) {
                this.initPageTreeData();
                this.$store.commit('designer/setPageMetadata', this.$DesignerCommonUtil.buildInitPageMetadata());
                this.$store.commit('designer/clearAllSelected');
                this.$store.commit('designer/setRightSidebarPageConfigFormName', '');
                this.$PnUtil.deleteUrlParams('page_id');
                this.$Message.success(result.data.message)
              }
            })
          }
        });
      },

      /**********************************菜单相关操作**********************************/

      otherDropdownClickHandler (name) {
        switch (name) {
          case 'clearCanvas':
            this.clearCanvas()
            break;
          case 'clearLocalStorage':
            this.clearLocalStorage()
            break;
          case 'showSourceDataDrawerVisible':
            this.sourceDataDrawerVisible = !this.sourceDataDrawerVisible
            break;
          case 'saveDraft':
            this.saveDraft()
            break;
          case 'loadDraft':
            this.loadDraft()
            break
        }
      },

      /**
       * 保存当前编辑页面
       */
      saveCurrentEditPage () {
        if (this.$store.state.designer.isAlongCompEditModel) {
          this.$Message.info('当前为独立组件编辑模式，无法保存，请先退出此模式')
        }else {
          this.$DesignerCommonUtil.saveCurrentEditPage(this.pageMetadata)
        }
      },

      /**
       * 初始化自动保存定时器
       */
      initAutoSavePageTimer () {
        if (this.autoSavePage) {
          this.autoSavePageTimer = setInterval(this.saveCurrentEditPage, this.autoSaveInterval * 60 * 1000)
        }else {
          clearTimeout(this.autoSavePageTimer)
        }
      },

      /**
       * 保存草稿
       */
      saveDraft () {
        this.$Modal.confirm({
          title: '提醒',
          content: '确认覆盖本地保存的草稿吗？',
          onOk: () => {
            localStorage.setItem('layoutCache', JSON.stringify(this.$store.state.designer.pageMetadata.layout));
            this.$Message.success('已将当前布局保存至草稿')
          }
        });
      },

      /**
       * 加载草稿
       */
      loadDraft () {
        if(localStorage.getItem('layoutCache')) {
          this.$store.commit('designer/setLayout', JSON.parse(localStorage.getItem('layoutCache')))
        }
      },

      /**
       * 清空画布
       */
      clearCanvas () {
        this.$DesignerCommonUtil.clearCanvas()
      },

      /**
       * 清空本地存储
       */
      clearLocalStorage () {
        this.$Modal.confirm({
          title: '提醒',
          content: '确认要清空本地存储吗？',
          onOk: () => {
            localStorage.clear();
            this.$Message.success('成功清空本地存储数据，建议重新刷新页面')
          }
        });
      },

      /**
       * 数据后退、撤销
       */
      stepBackward () {
        /*if(localStorage.getItem('layoutHistory')) {
          let layoutHistory = JSON.parse(localStorage.getItem('layoutHistory'));
          this.$store.commit('designer/setLayout', layoutHistory[0])
        }
        this.$EventBus.$emit('stepBackward')*/
        this.$store.dispatch('designer/stepBackward');
      },

      /**
       * 数据恢复
       */
      stepRecover () {
        this.$store.dispatch('designer/stepRecover');
      },

      /**
       * 打开主题美化窗口
       */
      openChangeThemeDrawer () {
        this.changeThemeDrawerVisible = !this.changeThemeDrawerVisible;
        this.$refs['changeThemeDrawer'].init(this.pageMetadata.theme_json)
      },

      /**
       * 打开收藏为模板窗口
       */
      openPageTemplateForm () {
        this.$refs['pageTemplateForm'].initPageMetadata(this.pageMetadata)
      },

      previewPage (target) {
        //console.log(this.pageMetadata);
        // 将当前打开页面的源数据存入本地存储
        localStorage.setItem('previewPageMetadata', JSON.stringify(this.pageMetadata));
        switch (target) {
          case 'self':
            this.previewFrameVisible = true;
            this.previewFrameSrc = this.$router.history.base + this.pageMetadata.path + '?preview=true';
            break;
          case 'blank':
            this.$PnUtil.openPageToBlank(this.pageMetadata.path, {preview: 'true'});
            break;
          default:
        }
      },

      openReleasePageFormModal () {
        this.releasePageFormModalVisible = !this.releasePageFormModalVisible
        this.$refs['releasePageFormModal'].init()
      },

      exportPage () {
        if (this.pageMetadata.id) {
          this.$Modal.confirm({
            title: '确认',
            content: '特别提醒：不要修改导出的文件的文件名，否则将无法在导入时正常进行解析',
            onOk: () => {
              let url = window.g.AXIOS_BASE_URL + '/page/exportPage?pageId=' + this.pageMetadata.id;
              this.$PnUtil.asyncHref(url, 'page_' + this.pageMetadata.id)
            }
          });
        }
      },

      openImportPageModal () {
        this.importPageModalVisible = !this.importPageModalVisible;
        this.$refs['importPageModal'].initProjectId(this.projectInfo.id)
      },

      importPageSuccessHandle () {
        this.importPageModalVisible = !this.importPageModalVisible;
        this.initPageTreeData()
      },

      openPageLogOperateDrawer() {
        this.$refs['PageLogOperateDrawer'].init()
      },

      quitAlongCompEditModel() {
        this.$DesignerCommonUtil.toggleAlongCompEditModel(false)
      }
    },
    computed: {
      ...mapFields({
        projectInfo: 'projectInfo',
        pageMetadata: 'pageMetadata',
        currentSelectLayoutItemId: 'currentSelectLayoutItemId',
        rightSidebarFuncCompConfigFormName: 'rightSidebarFuncCompConfigFormName',

        structureTreeSidebarCollapsed: 'structureTreeSidebarCollapsed',
        componentLibrarySidebarCollapsed: 'componentLibrarySidebarCollapsed',
        rightSidebarCollapsed: 'rightSidebarCollapsed',

        autoSavePage: 'autoSavePage',
        autoSaveInterval: 'autoSaveInterval',
        isAlongCompEditModel: 'isAlongCompEditModel'
      })
    },
    watch: {
      'pageMetadata.layout': {
        //监听源数据layout对象是否发生改变，发生改变将相关记录存储在vuex的layoutHistory中，给撤回与恢复操作提供原始数据
        handler: function (val, oldVal) {
          // 将布局信息存储在本地存储中，变量数组中只存两个对象，新进后出原则，再撤回操作中，永远只读第0个元素对象即为上一步操作
          /*if(!localStorage.getItem('layoutHistory')) {
            localStorage.setItem('layoutHistory', JSON.stringify([]))
          }else {
            let layoutHistory = JSON.parse(localStorage.getItem('layoutHistory'));
            if (layoutHistory.length >= 2) {
              layoutHistory = layoutHistory.slice(1)
            }
            layoutHistory.push(val);
            localStorage.setItem('layoutHistory', JSON.stringify(layoutHistory))
          }*/
          if (val.history) {
            delete val.history;
          }else {
            this.$store.commit('designer/addBackwardRecordItem', _.cloneDeep(val))
          }
        },
        deep: true
      },
      'autoSavePage': {
        handler: function () {
          this.initAutoSavePageTimer()
        },
        immediate: true
      }
    }
  }
</script>

<style lang="less" scoped>
  .back-home-btn {
    width: 20px;
    height: 100%;
    float: left;
    text-align: center;
    cursor: pointer;
    font-size: 18px;
    i {
      position: relative;
      top: -1px;
    }
  }
  .project-info-btn {
    width: auto;
    min-width: 60px;
    height: 100%;
    background-color: #ff5722;
    float: left;
    margin-right: 10px;
    padding: 0 10px;
    position: relative;
    &:hover {
      .project-tree-wrap {
        display: block;
      }
    }
    .project-tree-wrap {
      width: 400px;
      background-color: #424242;
      border-left: 2px solid #ff5722;
      border-bottom: 2px solid #ff5722;
      border-right: 2px solid #ff5722;
      position: absolute;
      left: 0px;
      box-sizing: border-box;
      padding: 10px;
      line-height: initial !important;
      display: none;
      -webkit-transition: all 0.2s ease-in-out 0s;
      transition: all 0.2s ease-in-out 0s;
      .page-tree-card-wrapper {
        max-height: 500px;
        overflow-y: auto;
        margin-top: 5px;
        padding: 5px;
        .page-tree-card {
          height: 30px;
          line-height: 30px;
          background-color: #616161;
          margin-bottom: 5px;
          .page-icon {
            width: 30px;
            height: 30px;
            background-color: #212121;
            text-align: center;
            float: left;
            &.active {
              background-color: #2196f3;
            }
          }
          .page-info {
            padding: 0px 40px;
            cursor: pointer;
          }
          .page-toolbar {
            float: right;
            .toolbar-btn {
              cursor: pointer;
              width: auto;
              height: 30px;
              padding: 0px 5px;
              background-color: #757575;
              display: inline-block;
              &:hover {
                background-color: #2196f3;
              }
            }
          }
          &:last-child {
            margin-bottom: 0px;
          }
          &:hover {
            outline: 1px solid #2196f3;
          }
        }
      }
    }
    span {
      color: #fff;
    }
  }
  .header-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    color: #fafafa;
  }
</style>
